package top.kangyaocoding.tech.service.Impl;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.kangyaocoding.tech.model.ChatSession;
import top.kangyaocoding.tech.service.IChatSessionService;

import java.util.List;

/**
 * 描述: 会话服务实现类
 *
 * @author K·Herbert
 * @since 2025-04-13 23:25
 */
@Slf4j
@Service
public class ChatSessionServiceImpl implements IChatSessionService {

    public static final String CHAT_SESSION_PREFIX = "CHAT_SESSION:";
    private final StringRedisTemplate stringRedisTemplate;

    public ChatSessionServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void saveSession(ChatSession chatSession, String userId) {
        String key = CHAT_SESSION_PREFIX + userId;
        stringRedisTemplate.opsForList().leftPush(key, JSON.toJSONString(chatSession));
    }

    @Override
    public List<ChatSession> getSessions(String userId) {
        String key = CHAT_SESSION_PREFIX + userId;
        List<String> strings = stringRedisTemplate.opsForList().range(key, 0, -1);
        if (strings != null) {
            return strings.stream().map(s -> JSON.parseObject(s, ChatSession.class)).toList();
        }
        return List.of();
    }
}
